//
//  TestContactsTableViewController.swift
//  ADKit_Example
//
//  Created by Adoma on 2020/10/30.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import ADKit

class TestContactsTableViewController: UITableViewController {
    
    struct Sections {
        var title: String
        var contacts: [Contact]
    }
    
    var sections: [Sections] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "测试获取通讯录"
        
        var temp: [String: [Contact]] = [:]
        
        for contact in ContactsManager.getContacts() {
            
            let key = String.init(contact.name.toPinYin().first ?? "#")
            
            if temp[key] == nil {
                temp[key] = []
            }
            temp[key]?.append(contact)
        }
        
        var sort = temp.sorted(by: { $0.key < $1.key })
        
        if let sharp = temp["#"] {
            sort.removeFirst()
            sort.append(contentsOf: ["#": sharp])
        }
        
        for contects in sort {
            sections.append(Sections.init(title: contects.key, contacts: contects.value))
        }
        
        tableView.reloadData()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sections[section].contacts.count
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].title
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
        if cell == nil {
            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "reuseIdentifier")
        }
        
        let contact = sections[indexPath.section].contacts[indexPath.row]

        cell.textLabel?.text = contact.name
        cell.detailTextLabel?.text = contact.phone
        cell.imageView?.image = contact.avatar
        
        return cell
    }

}
